import Vue from 'vue'
import JsEncrypt from 'jsencrypt'
import store from "../store/index.js"
import utils from '@/utils/utils.js';
import router from '@/router'
import md5 from 'js-md5';


Vue.prototype.utils = utils;
//生成签名
/* get current time */
function getCurrentTime() {
    return new Date().getTime();
}
export function getSign(oData, requestTime) {
	// store.getters.token
	if(!store.state.aeskey || !store.state.uid){
		router.replace({
			path: '/login',
			query: {from: router.currentRoute.name ? router.currentRoute.name : 'home'}//登录成功后跳入浏览的当前页面
		})
		return '';
	}
	if(oData.sign) delete oData.sign;
	oData.kAppKey = 'jksy2020';
	oData.kAppSecret = store.state.aeskey;
	oData.timeStamp = requestTime;
	var aKey = Object.keys(oData).sort();
	var sData = '';
    for (var i = 0; i < aKey.length; i++) {
		var sitem = function(){
			if (typeof oData[aKey[i]] == "object") {
				var kval = Object.keys(oData[aKey[i]]).sort();
				var sDs = '';
				for(var j=0; j < kval.length; j++){
					if(typeof oData[aKey[i]][kval[j]] == "object" || typeof oData[aKey[i]][kval[j]] == "undefined") continue;
					sDs += kval[j] + oData[aKey[i]][kval[j]];
				}
				return sDs;
			} else {
				return oData[aKey[i]];
			}
		}
		sData += aKey[i] + sitem();
	}
	
	delete oData.kAppKey;
	delete oData.kAppSecret;
	delete oData.timeStamp;
	return md5(sData);
}

//生成Token
export function genToken(){
    var oToken = JSON.parse(localStorage.getItem("token"));
    if(!oToken || !oToken.t || !oToken.e || (oToken.e + 2592000000 < getCurrentTime())){
        router.replace({
          path: '/login',
          query: {from: router.currentRoute.name ? router.currentRoute.name : 'home'}//登录成功后跳入浏览的当前页面
        })
        return '';
    }
    let publicKey = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCxwFju5VsN5E61YPjL/qD04hvqulhOxIzxWH2ZvSXZz/XY1xmwzq3avl3sKE6/rYMvTXMwULtMUaFRhvpsFFlmXHK0dOZ1/q7ruH1/sBT0Kx8aQafa5v02V4ARlR3hs85eznVWUfAW3EyGva+2uCVn869PtQfsf5ihdRT+FYGUBwIDAQAB';
    let encrypt = new JsEncrypt();
        encrypt.setPublicKey(
            //KEY RSA公钥
            publicKey
        );

    let rsa = encrypt.encrypt(JSON.stringify({uid:store.state.uid,timeStamp:Math.round(new Date().getTime() / 1000)}));
    let Base64 = require('js-base64').Base64;
    return Base64.encode(JSON.stringify({r:rsa,t:oToken.t,s: 'ios'}));
}

// 判断当前机型是否为ios
export function getPhoneType () {
  let ua = navigator.userAgent.toLowerCase()
  return ua.includes('iphone') ? 'ios' : 'android'
}

export default {
  getSign,
  genToken
}
